package bTree.LeetCode;

public class 生命游戏 {
    int[][] dir = new int[][]{{1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};

    public void gameOfLife(int[][] board) {
        int m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int i1 = 0; i1 < n; i1++) {
                int nums=cellNumber(i,i1,board);
                if (board[i][i1] == 0 && nums == 3) {
                    board[i][i1] = 3;//死变活
                }
                if (board[i][i1] == 1 && (nums < 2||nums>3)) {
                    board[i][i1] = 4;//活变死
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int i1 = 0; i1 < n; i1++) {
                if (board[i][i1] == 3) {
                    board[i][i1] = 1;
                }
                if (board[i][i1] == 4) {
                    board[i][i1] = 0;
                }
            }
        }
    }

    private int cellNumber(int i, int i1, int[][] board) {
        int cnt = 0;
        for (int i2 = 0; i2 < 8; i2++) {
            int nextX = i + dir[i2][0];
            int nextY = i1 + dir[i2][1];
            if (nextX < 0 || nextX >= board.length || nextY < 0 || nextY >= board[0].length) {
                continue;
            }
            if (board[nextX][nextY] == 1 || board[nextX][nextY] == 4) {
                cnt++;
            }
        }
        return cnt;
    }
}
